package rc.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import rc.Bank;

public abstract class BankDB implements Bank
{
	protected String url;

	protected String user;

	protected String password;

	public BankDB(List<Integer> balances, String url, String user,
			String password)
	{
		this.url = url;
		this.user = user;
		this.password = password;

		try {
			Class.forName("com.mysql.jdbc.Driver");

			Connection conn = DriverManager.getConnection(url, user, password);
			Statement stmt = conn.createStatement();
			stmt.executeUpdate("DROP TABLE IF EXISTS accounts");
			stmt.executeUpdate("CREATE TABLE accounts (id INT PRIMARY KEY, money INT) ENGINE=innodb");

			PreparedStatement prep = conn
					.prepareStatement("INSERT INTO accounts VALUES (?, ?)");

			int i = 0;

			for (int balance : balances) {
				prep.setInt(1, i);
				prep.setInt(2, balance);
				prep.execute();
				++i;
			}

			conn.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void showBalances()
	{
		try {
			int total = 0;
			Connection conn = DriverManager.getConnection(url, user, password);
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM accounts");

			while (rs.next()) {
				System.out.println("Account " + rs.getInt(1) + ": "
						+ rs.getInt(2));
				total += rs.getInt(2);
			}

			rs.close();
			conn.close();

			System.out.println("Total: " + total);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}